// index.js
const mqtt = require('../../utils/mqtt.js');
const app = getApp();

Page({
  data: {
    mqttConnected: false,
    deviceStatus: {
      temp: 25.5,
      hum: 60,
      light: 800,
      soil: 45,
      pump: false,
      lightCtrl: false,
      fan: false,
      autoMode: true,
      threshold: 30
    },
    lastWatering: '2小时前',
    nextWatering: '待定',
    waterLevel_h: '-200%', // 波浪动画的起始高度
    waterLevel_C: '-145%', // 波浪动画的结束高度
    waterLevelText: '45%', // 显示的湿度文本
    animation_name: 'loadingWave', // 动画名称
    lightIntensity: '30%' // 光照强度百分比
  },

  onLoad() {
    this.connectMQTT();
  },

  connectMQTT() {
    // 百度云MQTT连接信息
    const options = {
      host: 'asqvwdt.iot.gz.baidubce.com',
      port: 1883,
      clientId: 'test_iot',
      username: 'thingidp@asqvwdt|test_iot|0|MD5',
      password: 'c8c26b0d59f1838b3534e74fe2bf3d7d',
      reconnect: true
    };

    this.client = mqtt.connect(options);

    this.client.on('connect', () => {
      console.log('MQTT Connected');
      app.globalData.mqttConnected = true;
      this.setData({ mqttConnected: true });
      
      // 订阅控制主题
      this.client.subscribe('test_iot/#');
    });

    this.client.on('message', (topic, message) => {
      if (topic === 'test_iot/#') {
        const data = JSON.parse(message.toString());
        this.updateDeviceStatus(data);
      }
    });

    this.client.on('error', (error) => {
      console.error('MQTT Error:', error);
      wx.showToast({
        title: '连接失败',
        icon: 'none'
      });
    });
  },

  updateDeviceStatus(newStatus) {
    const deviceStatus = {...this.data.deviceStatus, ...newStatus};
    this.setData({ deviceStatus });
    app.globalData.deviceStatus = deviceStatus;
    
    // 更新浇水时间
    if (newStatus.pump && !this.data.deviceStatus.pump) {
      this.setData({ lastWatering: '刚刚' });
    }
    
    // 如果土壤湿度有更新，则更新湿度计
    if (newStatus.soil !== undefined) {
      this.updateHumidityGauge(newStatus.soil);
    }
    
    // 如果光照强度有更新，则更新光照显示
    if (newStatus.light !== undefined) {
      this.updateLightIntensity(newStatus.light);
    }
  },
  
  // 更新光照强度显示
  updateLightIntensity: function (lightValue) {
    // 假设光照强度范围是0-1000lux
    const maxLight = 1000;
    let percentage = Math.min((lightValue / maxLight) * 100, 100);
    percentage = Math.max(percentage, 0); // 确保不小于0
    this.setData({
      lightIntensity: `${percentage}%`
    });
  },
  
  // 更新湿度计波浪效果
  updateHumidityGauge: function (level) {
    const percentage = level; // 将水位转换为百分比
    const waveHeight = `${100 - percentage}%`;
    const changeHeight = `${100 - level}%`;
    const wavetext = `${percentage}%`;
    this.setData({
      waterLevel_h: waveHeight, // 上一次的结束位置作为新的开始位置
      waterLevel_C: changeHeight, // 新的结束位置
      waterLevelText: wavetext,
      animation_name: 'loadingWave' // 设置动画名称
    });
  },



  toggleAutoMode(e) {
    const autoMode = e.detail.value;
    this.sendControlCommand({ autoMode });
    this.setData({ 
      'deviceStatus.autoMode': autoMode 
    });
  },

  setThreshold(e) {
    const threshold = e.detail.value;
    this.sendControlCommand({ threshold });
    this.setData({ 
      'deviceStatus.threshold': threshold 
    });
  },

  togglePump(e) {
    const pump = e.detail.value;
    this.sendControlCommand({ pump });
    this.setData({ 
      'deviceStatus.pump': pump 
    });
  },

  toggleLight(e) {
    const lightCtrl = e.detail.value;
    this.sendControlCommand({ lightCtrl });
    this.setData({ 
      'deviceStatus.lightCtrl': lightCtrl 
    });
  },

  toggleFan(e) {
    const fan = e.detail.value;
    this.sendControlCommand({ fan });
    this.setData({ 
      'deviceStatus.fan': fan 
    });
  },

  sendControlCommand(data) {
    if (!this.data.mqttConnected) {
      wx.showToast({
        title: '设备未连接',
        icon: 'none'
      });
      return;
    }
    
    this.client.publish('test_iot/soil/control', JSON.stringify(data));
  },

  goSettings() {
    wx.navigateTo({
      url: '/pages/settings/settings'
    });
  }
});